﻿using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;


namespace CodeGenerator.Common
{
    public class FileHelper
    {
        public static void Copy(DirectoryInfo from, DirectoryInfo to)
        {
            if (to.FullName.StartsWith(from.FullName, StringComparison.CurrentCultureIgnoreCase))
            {
                throw new Exception("父目录不能拷贝到子目录！");
            }
            if (from.Exists)
            {
                if (!to.Exists)
                {
                    to.Create();
                }
                FileInfo[] files = from.GetFiles();
                for (int i = 0; i < files.Length; i++)
                {
                    File.Copy(files[i].FullName, Path.Combine(to.FullName, files[i].Name), true);
                }
                DirectoryInfo[] directories = from.GetDirectories();
                for (int j = 0; j < directories.Length; j++)
                {
                    Copy(directories[j].FullName, Path.Combine(to.FullName, directories[j].Name));
                }
            }
        }

        public static void Copy(string fromDir, string toDir)
        {
            DirectoryInfo from = new DirectoryInfo(fromDir);
            DirectoryInfo to = new DirectoryInfo(toDir);
            Copy(from, to);
        }

        public static string Read(string filePath, Encoding encoding = null)
        {
            if (File.Exists(filePath))
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }
                return File.ReadAllText(filePath, encoding);
            }
            return "";
        }

        public static FileStream ReadStream(string fileName)
        {
            FileStream stream = null;
            if (!string.IsNullOrEmpty(fileName) && File.Exists(fileName))
            {
                stream = new FileStream(fileName, FileMode.Open);
            }
            return stream;
        }

        public static bool Write(string filePath, string content, Encoding encoding = null)
        {
            File.Delete(filePath);
            using (FileStream stream = new FileStream(filePath, FileMode.Append, FileAccess.Write))
            {
                if (encoding == null)
                {
                    encoding = Encoding.UTF8;
                }
                StreamWriter writer = new StreamWriter(stream, encoding);
                writer.Write(content);
                writer.Flush();
                writer.Close();
            }
            return true;
        }
    }
}
